<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-16
 * Time: 17:53
 */

namespace app\api\service\member;

use app\api\model\MdbUser;
use app\api\model\MdbUserMoney;
use LinCmsTp5\exception\ParameterException;
use think\Db;
use think\Exception;

class UpdateUser
{
    // 用户ID
    private $uid;

    // 用户信息
    private $user;

    // 类型
    private $type;

    // 金额
    private $money;

    function __construct($type,$money,$uid)
    {
        $this->type = $type;
        $this->money = $money;
        $this->uid = $uid;
    }

    // 更新信息入口
    public function updateData()
    {
        $this->judgeData();
        Db::startTrans();
        try{
            MdbUserMoney::create([
                'mdb_user_id' => $this->uid,
                'money' => $this->money,
                'type' => $this->type,
                'user_money' => $this->user['money'],
            ]);
            if($this->type == 1) {
                MdbUser::where('id',$this->uid)->update([
                    'money' => round($this->money + $this->user['money'],2)
                ]);
            } else {
                MdbUser::where('id',$this->uid)->update([
                    'money' => round($this->user['money'] - $this->money,2)
                ]);
            }
            Db::commit();
            return writeJson(201, [], '操作成功!');
        }
        catch (Exception $ex) {
            Db::rollback();
            throw $ex;
        }
    }

    // 判断数据
    private function judgeData()
    {
        $this->user = MdbUser::get($this->uid);
        if(!$this->user) {
            throw new ParameterException([
                'msg' => [
                    'member' => '请重新选择用户信息'
                ]
            ]);
        }
        if($this->user['status'] == 2) {
            throw new ParameterException([
                'msg' => [
                    'member' => '信息已同步'
                ]
            ]);
        }
        if($this->type != 1) {
            if($this->type != 2) {
                throw new ParameterException([
                    'msg' => [
                        'member' => '操作类型错误'
                    ]
                ]);
            } else {
                if($this->money > $this->user['money']) {
                    throw new ParameterException([
                        'msg' => [
                            'member' => '用户余额不足'
                        ]
                    ]);
                }
            }
        }
        $this->money = round($this->money,2);
        if($this->money <= 0) {
            throw new ParameterException([
                'msg' => [
                    'member' => '请输入正确的金额'
                ]
            ]);
        }
    }
}